package ez

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/dreamwood/ez-go/ss"
	"gitee.com/dreamwood/ez-go/tools"
	"runtime"
)

func Print(err error) {
	if err != nil {
		_, f, l, _ := runtime.Caller(1)
		_ = fmt.Sprintf("[EZ-ERROR] %s %s:%d\n%s",
			tools.GetDateYMDHIS("-", ":", " "),
			f, l, err.Error(),
		)
	}
}

func Try(err error) bool {
	if err != nil {
		println(err.Error())
		return true
	} else {
		return false
	}
}
func ErrLog(err error) bool {
	if err != nil {
		pc, f, l, _ := runtime.Caller(1)
		SendBackgroundErrorLog(err.Error(), ss.M{
			"File": f,
			"Line": l,
			"Func": runtime.FuncForPC(pc).Name(),
		})
		return true
	} else {
		return false
	}
}

func Get(err error) string {
	if err != nil {
		return err.Error()
	} else {
		return ""
	}
}

type ErrLogDoc struct {
	Content string
	Trace   string
	Dumps   []string
}

func ErrToMgo(err error, depth int) {
	if err != nil {
		doc := ErrLogDoc{
			Content: err.Error(),
		}
		//加入固定格式的信息
		if depth > 0 {
			_, f, l, _ := runtime.Caller(depth)
			doc.Trace = fmt.Sprintf("[EZ-ERROR] %s %s:%d",
				tools.GetDateYMDHIS("-", ":", " "),
				f, l,
			)
		}
		_, e := DBMongo.
			Collection(EzErrorLogDoc).
			InsertOne(context.TODO(), doc)
		if e != nil {
			println(e)
		}
	}
}

func ErrToNsq(err error, depth int) {
	if err != nil {
		data := err.Error()
		if depth > 0 {
			_, f, l, _ := runtime.Caller(depth)
			data = fmt.Sprintf("[EZ-ERROR] %s %s:%d\n%s",
				tools.GetDateYMDHIS("-", ":", " "),
				f, l,
				err.Error(),
			)
		}
		e := NsqProducer.Publish(EzErrorReport, []byte(data))
		if e != nil {
			println(e)
		}
	}
}

func SendBackgroundErrorLog(message string, data ss.M) {
	log := new(ErrorLog)
	log.App = ConfigService.AppId
	log.Code = "500"
	log.State = 0
	log.Message = message
	log.Data = data
	content, _ := json.Marshal(log)
	_ = NsqProducer.Publish(EzTopicErrorLog, content)
}
